package com.hjq.exception;

import com.hjq.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 * 在spring项目中，异常通常不会直接处理，而是向外抛出，直到controller层，在通过controller层的aop进行统一处理
 */
// @ControllerAdvice
// @ResponseBody
// 组合
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public Result<Object> handleException(Exception e) {
        e.printStackTrace();
        log.info("Exception异常,{}",e.getMessage());
        return Result.error("服务器异常");
    }
    @ExceptionHandler(RuntimeException.class)
    public Result<Object> handleRuntimeException(RuntimeException e) {
        e.printStackTrace();
        log.info("RuntimeException异常,{}",e.getMessage());
        return Result.error("服务器异常");
    }
    @ExceptionHandler(DuplicateKeyException.class)
    public Result<Object> handleDuplicateKeyException(DuplicateKeyException e) {
        e.printStackTrace();
        String eMessage = e.getMessage();
        log.info("DuplicateKey异常,{}",eMessage);
        String[] split = eMessage.substring(eMessage.indexOf("Duplicate entry")).split(" ");

        return Result.error(split[2]+"已经存在");
    }
    @ExceptionHandler(ServiceException.class)
    public Result<Object> handleException(ServiceException e) {
        e.printStackTrace();
        log.info("Exception异常,{}",e.getMessage());
        return Result.error(e.getMessage());
    }
}
